//
//  SCEmoticonViewModel.swift
//  weibo
//
//  Created by 阿城 on 15/12/15.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

class SCEmoticonViewModel: NSObject {
    
    //归档路径
    let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("recent.archive")
    
    
    lazy var contentEmoticon: [[[SCEmoticonModel]]] = {
        
        var content = [[[SCEmoticonModel]]]()
        
        let resentEmoticons = [self.resentEmoticons]
        let defaultEmoticons = self.setPages(self.defaultEmoticons)
        let emojiEmoticons = self.setPages(self.emojiEmoticons)
        let lxhEmoticons = self.setPages(self.lxhEmoticons)
        
        content += [resentEmoticons, defaultEmoticons, emojiEmoticons, lxhEmoticons]
        return content
    }()
    
    static let shareEmoticons: SCEmoticonViewModel = SCEmoticonViewModel()
    
    private let pageNumber = 20
    
    
    func getBundlePath(name: String) -> String{
        var path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        path.appendContentsOf("/Contents/Resources/\(name)")
        return path
    }
    
    private func getEmoticonsWithName(name: String) -> [SCEmoticonModel]{
        let path = getBundlePath(name).stringByAppendingString("/info.plist")
        let dicts = NSArray(contentsOfFile: path)!
        var emoticons = [SCEmoticonModel]()
        for dict in dicts{
            let emoticon = SCEmoticonModel(dict: dict as! [String : AnyObject])
            //刷选emoji
            if let imgName = emoticon.png{
                //计算图片路劲
                emoticon.path = getBundlePath(name).stringByAppendingString("/\(imgName)")
                //保存归属
                emoticon.belong = name
                
            }
            emoticons.append(emoticon)
        }

        return emoticons
    }
    
    //表情分页
    private func setPages(emoticons:[SCEmoticonModel])->[[SCEmoticonModel]]{
        //计算多少页
        let num = (emoticons.count - 1) / pageNumber + 1
        var content = [[SCEmoticonModel]]()
        //截取20个
        for i in 0..<num {
            //计算长度,避免越界
            let len = pageNumber * (i + 1) < emoticons.count ? pageNumber : emoticons.count - pageNumber * i
            let subContent = (emoticons as NSArray).subarrayWithRange(NSRange(location: i * pageNumber, length: len)) as! [SCEmoticonModel]
            content.append(subContent)
        }
        return content
    }
    
    // MARK: - 加载表情数组
    private lazy var defaultEmoticons: [SCEmoticonModel] = self.getEmoticonsWithName("default")
    
    private lazy var emojiEmoticons: [SCEmoticonModel] = self.getEmoticonsWithName("emoji")
    
    private lazy var lxhEmoticons: [SCEmoticonModel] = self.getEmoticonsWithName("lxh")
    
    private lazy var resentEmoticons:[SCEmoticonModel] = {
        guard let resent = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? [SCEmoticonModel] else{
            return [SCEmoticonModel]()
        }
        //回复图片路径
        for emo in resent where emo.png != nil{
            emo.path = self.getBundlePath(emo.belong!).stringByAppendingString("/\(emo.png!)")
        }
        return resent
    }()
    
    //归档
    func saveTheResent(button: SCEmoticonButton){
        //去除重复
        var pageOne = contentEmoticon[0][0]
        let temArr = NSMutableArray(array: pageOne)
        temArr.removeObject(button.emoticon!)
        pageOne = temArr.copy() as! Array
        //插入最新
        pageOne.insert(button.emoticon!, atIndex: 0)
        //保持不越界
        if pageOne.count > 20{
            pageOne.removeLast()
        }
        //更新数据
        contentEmoticon[0][0] = pageOne
        //归档
        NSKeyedArchiver.archiveRootObject(pageOne, toFile: path)
    }
    
    func findEmoticon(name: String) -> SCEmoticonModel?{
        
        let predicate = NSPredicate(format: "chs == %@", name)
        var emoticons = [SCEmoticonModel]()
        emoticons.appendContentsOf(defaultEmoticons)
        emoticons.appendContentsOf(lxhEmoticons)
        
        let arr = (emoticons as NSArray).filteredArrayUsingPredicate(predicate)
        return arr.first as? SCEmoticonModel
    }
    
}
